import { Tooltip, Badge, Space } from 'antd';
import React, { useEffect } from 'react';
import { useModel, history } from 'umi';
import Avatar from './AvatarDropdown';
import styles from './index.less';
import ChangePasswordForm from './ChangePasswordForm';
import IconFont from '@/components/IconFont';
import classnames from 'classnames';
import userAlarmHoxModel from '@/pages/Alarm/useHoxModel';
import WebsocketHeartbeatJs from '@/utils/webscoket';

export type SiderTheme = 'light' | 'dark';

// const ENVTagColor = {
//   dev: 'orange',
//   test: 'green',
//   pre: '#87d068',
// };
const createWebSocket = async (updateAlarmCount: () => void, actionRef: any) => {
  let firstHeartbeat = true;

  const url = `ws://${localStorage.getItem('webSocket')}/${localStorage.getItem('token')}`;
  let websocketHeartbeatJs = new WebsocketHeartbeatJs({
    url: url,
    pingTimeout: 60000,
    pongTimeout: 60000,
  });
  websocketHeartbeatJs.onopen = function () {
    console.log('WebSocket连接成功!');
  };
  websocketHeartbeatJs.onclose = function () {
    console.log('WebSocket断开!');
  };
  websocketHeartbeatJs.onerror = function () {
    console.log('WebSocket异常!');
  };
  websocketHeartbeatJs.onmessage = function (e: any) {
    if (e.data !== websocketHeartbeatJs.opts.pingMsg && e.data) {
      console.log(e.data);
      updateAlarmCount();
      actionRef.current?.reload();
    }
    if (e.data == websocketHeartbeatJs.opts.pingMsg && firstHeartbeat) {
      setTimeout(() => {
        console.log(
          `Close your network, wait ${
            (websocketHeartbeatJs.opts.pingTimeout as number) +
            (websocketHeartbeatJs.opts.pongTimeout as number)
          }+ ms, websocket will reconnect`,
          'cadetblue',
        );
      }, 1500);
      firstHeartbeat = false;
    }
  };
  websocketHeartbeatJs.onreconnect = function () {
    console.log(`正在重连中...`);
  };
  return websocketHeartbeatJs;
};

const GlobalHeaderRight: React.FC<{}> = () => {
  const { initialState } = useModel('@@initialState');
  const {
    getRunAlarmCount,
    realtimeActionRef: actionRef,
    runAlarmCount = 0,
  } = userAlarmHoxModel((model) => [model.runAlarmCount]);
  useEffect(() => {
    getRunAlarmCount();
    const updateAlarmCount = () => {
      getRunAlarmCount();
    };
    try {
      createWebSocket(updateAlarmCount, actionRef);
    } catch {
      console.log('webscoket 连接失败!');
    }
  }, []);

  if (!initialState || !initialState.settings) {
    return null;
  }

  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }
  return (
    <>
      <Space className={className}>
        <Tooltip title="告警数量">
          <span
            className={classnames(styles.action, styles.alarm)}
            onClick={() => {
              history.push('/entry/entranceGuardManagement/alarm');
            }}
          >
            <Badge count={runAlarmCount} showZero overflowCount={99} offset={[2, -4]}>
              <IconFont type={'icontixing'} />
            </Badge>
          </span>
        </Tooltip>
        <Avatar />
      </Space>
      <ChangePasswordForm />
    </>
  );
};
export default GlobalHeaderRight;
